package piblanes;

import java.util.ArrayList;

/**
 * This is the main class of game.
 * It concludes all information about game (such as player postions, field size, etc)
 * and it's task is to compute all changes in game. It communicates with 'contollers',
 * which controles the players (AI, usual player or network player).
 */

public class Game {
    public Game() {
        players.add(new Player());
        players.add(new Player());
    }

    private void performPlayerAction(Player player, ControllerSignal signal) {
        switch (signal){
            case RIGHT:
                player.getGeometricalState().addAngle(-angleStep);
                break;
            case LEFT:
                player.getGeometricalState().addAngle(angleStep);
                break;
        }
    }

    private void handlePlayers() {
        for (Player currentPlayer : players) {
            if (currentPlayer.hasAction()) {
                performPlayerAction(currentPlayer, currentPlayer.getFirstAction());
                currentPlayer.removeFirstAction();
            }
            
            double velocity = currentPlayer.getVelocity();
            double angle = currentPlayer.getGeometricalState().getAngle();
            currentPlayer.move(velocity * Math.cos(angle), velocity * Math.sin(angle));

            
            double curx = currentPlayer.getGeometricalState().getX();
            double cury = currentPlayer.getGeometricalState().getY();

            if (curx < 0) currentPlayer.getGeometricalState().setX(FIELD_WIDTH + curx);
            if (curx > FIELD_WIDTH) currentPlayer.getGeometricalState().setX(curx - FIELD_WIDTH);

            if (cury < 0) currentPlayer.getGeometricalState().setY(0);
            if (cury > FIELD_HEIGHT) currentPlayer.getGeometricalState().setY(FIELD_HEIGHT);
        }
    }

    // The main method. Every time it's called class compute all changes,
    // handles players' control, etc
    public void tick() {
        handlePlayers();
    }

    public ArrayList<Player> getPlayers() {return players;}

    private ArrayList<Player> players = new ArrayList<Player>();
    public static final double angleStep = Math.PI / 12;
    public static final double FIELD_WIDTH = 100;
    public static final double FIELD_HEIGHT = 100;
}

